package pro.cherish.knowledgeumldesignpattern.designPattern.com.cherish.singleton;

import java.io.*;
import java.lang.reflect.Constructor;

/**
 * 测试反射和反序列化破解
 */
public class Client2 {
    public static void main(String [] args) throws Exception {
        T06 instance = T06.getInstance();
        T06 instance1 = T06.getInstance();
        System.out.println(instance);
        System.out.println(instance1);



//        Class<T06> clazz=  (Class<T06>) Class.forName("com.cherish.singleton.T06");
//        Constructor<T06> c = clazz.getDeclaredConstructor(null);
//        c.setAccessible(true);
//        T06 t06 = c.newInstance();
//        T06 t062 = c.newInstance();
//        System.out.println(t06);
//        System.out.println(t062);
// 通过反射方式直接调用私有构造器，跳过了单例
// pro.cherish.knowledgeumldesignpattern.designPattern.com.cherish.singleton.T06@4554617c
//com.cherish.singleton.T06@4554617c
//com.cherish.singleton.T06@74a14482
//com.cherish.singleton.T06@1540e19d
//        解决方案：
//            private T06(){
//            if(instance!=null){
//                throw new RuntimeException("手动抛出异常");
//            }
//        }


//        通过序列化、反序列化构造多个对象
//        序列化
        FileOutputStream fos=new FileOutputStream("d:/tmp.txt");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(instance);
        oos.close();
        fos.close();
        /* 反序列化 */
        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("d:/tmp.txt"));
        T06 o =(T06) objectInputStream.readObject();
        System.out.println(o);
        objectInputStream.close();
    }
//   反序列化方式破解了单例
// pro.cherish.knowledgeumldesignpattern.designPattern.com.cherish.singleton.T06@4554617c
//com.cherish.singleton.T06@4554617c
//com.cherish.singleton.T06@568db2f2

//解决方案：
//    反序列化时，直接返回该对象,不需要将反序列化的新对象返回
//private Object readResolve ()throws ObjectStreamException {
//    return instance;
//}

}
